package com.pinyoumei.app.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pinyoumei.app.R;
import com.pinyoumei.app.bean.SettingBean;
import com.pinyoumei.app.bean.VersionBean;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.AppManager;
import com.pinyoumei.app.utils.ClearCahceUtils;
import com.pinyoumei.app.utils.EventBusUtils;
import com.pinyoumei.app.utils.FileMD5;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.ToastUtils;
import com.pinyoumei.app.utils.Utils;
import com.pinyoumei.app.utils.event.ReshEvent;
import com.pinyoumei.app.view.ClearCacheDialog;
import com.pinyoumei.app.view.dialog.APPUpdateDialog;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.db.CacheManager;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.functions.Consumer;

/**
 * Created by Administrator on 2021-08-14.
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2021-08-14        Administrator             新增Person类
 * 2021-08-14        Administrator             增加sex属性
 */
public class SettingActivity extends BaseActivity implements View.OnClickListener {
    protected AppManager appManager = AppManager.getInstance();
    private APPUpdateDialog appUpdateDialog;
    //apk的文件地址
    private String mSavePath;
    //apk的名称
    private String apk_name;
    //apk的文件
    private File apkFile;
    //版本更新的下载地址apk在服务器上的地址
    private String url_path = "";
    //服务器返回的apk的MD5值
    private String apkMD5;

    private TextView tv_user_phone;
    private TextView tvCache;
    private TextView tv_user_alipay_info;
    private ClearCacheDialog clearCacheDialog;
    private TextView tv_version;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBusUtils.register(this);
        setContentView(R.layout.activity_settting);
        InitWidget();
        InitData();
    }


    @Subscribe(threadMode = ThreadMode.MAIN, priority = 1)
    public void onMessageEventMain(ReshEvent event) {
        if (event != null ) {

            InitData();
        }
    }
    private void InitWidget() {

        ImageView iv_close = findViewById(R.id.iv_close);
        iv_close.setOnClickListener(this);
        RelativeLayout rl_Account = findViewById(R.id.rl_Account);
        rl_Account.setOnClickListener(this);

        RelativeLayout rl_cache = findViewById(R.id.rl_cache);
        rl_cache.setOnClickListener(this);
        RelativeLayout rl_user_info = findViewById(R.id.rl_user_info);
        rl_user_info.setOnClickListener(this);

        RelativeLayout rl_address = findViewById(R.id.rl_address);
        rl_address.setOnClickListener(this);
        RelativeLayout rl_version = findViewById(R.id.rl_version);
        rl_version.setOnClickListener(this);

        RelativeLayout rl_login_psd = findViewById(R.id.rl_login_psd);
        rl_login_psd.setOnClickListener(this);

        Button bt_login_out = findViewById(R.id.bt_login_out);
        bt_login_out.setOnClickListener(this);
        RelativeLayout rl_ali = findViewById(R.id.rl_ali);
        rl_ali.setOnClickListener(this);
        RelativeLayout rl_chage = findViewById(R.id.rl_chage);
        rl_chage.setOnClickListener(this);

        RelativeLayout rl_buy_pwd = findViewById(R.id.rl_buy_pwd);
        rl_buy_pwd.setOnClickListener(this);

        tvCache = findViewById(R.id.tvCache);
        tv_version = findViewById(R.id.tv_version);
        tv_user_phone = findViewById(R.id.tv_user_phone);
        tv_user_alipay_info = findViewById(R.id.tv_user_alipay_info);

        tv_version.setText( "版本信息v." + getAppVersionCode());
        try {
            if (ClearCahceUtils.getTotalCacheSize(this).contains("0.0Byte")) {
                tvCache.setText("0.00MB");
            } else {
                tvCache.setText(ClearCahceUtils.getTotalCacheSize(this));
            }

        } catch (Exception e) {

        }
        clearCacheDialog = new ClearCacheDialog(this, R.layout.item_layout_clearcache, new int[]{});
        clearCacheDialog.setOnClickListener(new ClearCacheDialog.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.relative_sure:
                        ClearCahceUtils.clearAllCache(SettingActivity.this);
                        CacheManager.getInstance().clear();
                        try {
                            tvCache.setText("0.00MB");
                        } catch (Exception e) {

                        }
                        ToastUtils.showShort("清除成功");
                        clearCacheDialog.dismiss();
                        break;
                    case R.id.relative_cancle:
                        clearCacheDialog.dismiss();
                        break;
                }
            }
        });

    }



    private void InitData() {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(SettingActivity.this));

        OkGo.<String>post(Constants.SETTING_CENTER)
                .params("user_id", SPUtils.getAppUserId(SettingActivity.this))
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }


                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);

                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();

                        SettingBean settingBean = gson.fromJson(response.body(), SettingBean.class);

                        if (settingBean.getCode() >= 0) {

                            tv_user_phone.setText("(当前: " + settingBean.getResult().getUser_phone() +")");
                            if (!TextUtils.isEmpty(settingBean.getResult().getUser_alipay_info())){
                                tv_user_alipay_info.setText("(当前: " + settingBean.getResult().getUser_alipay_info() +")");

                            }
                        } else {
                            ToastUtils.showShort(settingBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }
                });


    }

    /**
     * 返回当前程序版本号
     */
    public String getAppVersionCode() {
        int versioncode = 0;
        try {
            PackageManager pm = getPackageManager();
            PackageInfo pi = pm.getPackageInfo(getPackageName(), 0);
            // versionName = pi.versionName;
            versioncode = pi.versionCode;
        } catch (Exception e) {

        }
        return versioncode + "";
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.iv_close:
                finish();
                break;

            case R.id.rl_address:
                startActivity(new Intent(SettingActivity.this, AddressManagementActivity.class));
                break;

            case R.id.rl_cache:
                clearCacheDialog.show();
                break;
            case R.id.rl_user_info:
                startActivity(new Intent(SettingActivity.this, UserInfoActivity.class));
                break;

                case R.id.rl_version:
                    appVersion();
                break;

                case R.id.rl_login_psd:
                    startActivity(new Intent(SettingActivity.this, ChangeLoginPswActivity.class));
                break;

                case R.id.rl_buy_pwd:
                    startActivity(new Intent(SettingActivity.this, PayPassWordActivity.class));
                break;

                case R.id.rl_Account:
                    startActivity(new Intent(SettingActivity.this, SwitchAccountActivity.class));
                break;
        case R.id.rl_ali:
                    startActivity(new Intent(SettingActivity.this, AliPayPasswordActivity.class));
                break;
     case R.id.rl_chage:
                    startActivity(new Intent(SettingActivity.this, ChangePhoneActivity.class));
                break;


            case R.id.bt_login_out:
                SPUtils.clearAppUserid(SettingActivity.this);
                SPUtils.clearUserPhone(SettingActivity.this);
                startActivity(new Intent(SettingActivity.this, LoginActivity.class));
                finish();
                appManager.killAllActivity();

                break;

            default:
                break;
        }
    }


    private void appVersion() {

        Map<String,Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(SettingActivity.this));
        map.put("type", 1);
        map.put("version_num", Utils.getVersionCode(SettingActivity.this));


        OkGo.<String>post( Constants.APPVERSION_CHECK)
                .params("user_id", SPUtils.getAppUserId(SettingActivity.this))
                .params("type", 1)
                .params("version_num", Utils.getVersionCode(SettingActivity.this))
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {



                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }


                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        VersionBean agencyRuleBean = gson.fromJson(response.body(), VersionBean.class);
                        if (agencyRuleBean.getCode() > 0 ){

                            url_path = agencyRuleBean.getResult().getApp_info().getApp_download_address();
                            apkMD5 = agencyRuleBean.getResult().getApp_info().getRemark();
                            //版本更新Dialog下载APK
                            appUpdateDialog = new APPUpdateDialog(SettingActivity.this, agencyRuleBean.getResult().getApp_info().getDescription());

                            appUpdateDialog.setOnClickListener(new APPUpdateDialog.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    switch (view.getId()) {
                                        case R.id.relative_app_update://点击是版本更新按钮
                                            if (agencyRuleBean.getResult().getApp_info().getApp_download_address().equals("")) {
                                                Toast.makeText(SettingActivity.this, "下载链接获取失败!", Toast.LENGTH_SHORT).show();
                                                return;
                                            }
                                            RxPermissions rxPermission = new RxPermissions(SettingActivity.this);
                                            rxPermission.requestEach(
                                                    //写入SD卡权限
                                                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                                            ).subscribe(new Consumer<Permission>() {
                                                @Override
                                                public void accept(Permission permission) throws Exception {
                                                    if (permission.granted) {
                                                        // 用户已经写入SD卡权限
                                                        if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permission.name)) {

                                                            boolean haveInstallPermission;
                                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                                                //先获取是否有安装未知来源应用的权限
                                                                haveInstallPermission = getPackageManager().canRequestPackageInstalls();
                                                                if (!haveInstallPermission) {
                                                                    //8.0没有权限
                                                                    AlertDialog.Builder builder = new AlertDialog.Builder(SettingActivity.this);
                                                                    builder.setTitle("安装应用需要打开未知来源权限，请去设置中开启权限");
                                                                    builder.setPositiveButton("开启", new DialogInterface.OnClickListener() {
                                                                        @Override
                                                                        public void onClick(DialogInterface dialog, int which) {
                                                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                                                                startInstallPermissionSettingActivity();
                                                                            }
                                                                        }
                                                                    });

                                                                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                                        @Override
                                                                        public void onClick(DialogInterface dialog, int which) {
                                                                            Toast.makeText(SettingActivity.this, "取消将无法正常安装！", Toast.LENGTH_SHORT).show();
                                                                        }
                                                                    });
                                                                    builder.create().show();
                                                                    return;
                                                                } else {
                                                                    //8.0有未知来源权限
                                                                    installApk();
                                                                }
                                                            } else {
                                                                // 下载APK
                                                                installApk();
                                                            }


                                                        }
                                                    } else {//如果用户没有同意那么需要弹出提示框让用户去解决
                                                        Toast.makeText(SettingActivity.this, "请打开读写手机存储权限!", Toast.LENGTH_SHORT).show();
                                                    }
                                                }
                                            });
                                            break;
                                        default:
                                    }
                                }
                            });


                            switch (agencyRuleBean.getResult().getIs_show_update()) {

                                case 1:
                                    //最新版本 强制更新
                                    appUpdateDialog.setCancelable(false);
                                    appUpdateDialog.setCanceledOnTouchOutside(false);
                                    appUpdateDialog.show();

                                    break;


                            }










                        }else{
                            ToastUtils.showShort(agencyRuleBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }
                });
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startInstallPermissionSettingActivity() {
        Uri packageURI = Uri.parse("package:" + getPackageName());
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        startActivityForResult(intent, 10086);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10086 && resultCode == RESULT_OK) {
            installApk();
        }
    }


    private void installApk() {
        //这个地方涉及到访问内存的权限问题 需要动态申请内存权限
        mSavePath = Environment.getExternalStorageDirectory().getPath() + "/sdcard/newpurseAPK/";
        File file = new File(mSavePath);
        // 判断文件目录是否存在
        if (!file.exists()) {
            file.mkdir();
        }
        apk_name = getFileName(url_path);//返回一个后缀名称为XX.apk字符串
        apkFile = new File(mSavePath, apk_name);
        File mFile = new File(mSavePath + apk_name);
        // 判断文件目录是否存在
        if (mFile.exists()) {//
            mFile.delete();
        }
        //显示进度条
        appUpdateDialog.showProgress();
        //下载

        OkGo.<File>get(url_path)//
                .tag(this)//
                .execute(new FileCallback(mSavePath, apk_name) {

                    @Override
                    public void onStart(Request<File, ? extends Request> request) {

                    }

                    @Override
                    public void onSuccess(Response<File> response) {
                        if (file.exists()) {//如果文件下载成功 先进行MD5校验
                            //下载的文件算出MD5值与服务器返回的MD5值进行比较 一致说明成功 不一致说明失败
                            if (FileMD5.verifyInstallPackage(mSavePath + apk_name, apkMD5)) {
                                Toast.makeText(SettingActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
                                appUpdateDialog.dismiss();
                                Intent intent = new Intent(Intent.ACTION_VIEW);
                                //版本在7.0以上是不能直接通过uri访问的
                                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
                                    File file_path = (new File(mSavePath + apk_name));
                                    // 由于没有在Activity环境下启动Activity,设置下面的标签
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    //参数1:上下文, 参数2:Provider主机地址 和配置文件中保持一致,参数3:共享的文件
                                    Uri apkUri = FileProvider.getUriForFile(SettingActivity.this, "com.pinyoumei.app.fileprovider", file_path);
                                    //添加这一句表示对目标应用临时授权该Uri所代表的文件
                                    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                } else {
                                    intent.setDataAndType(Uri.fromFile(new File(mSavePath + apk_name)), "application/vnd.android.package-archive");
                                }
                                SettingActivity.this.startActivity(intent);

                            } else {
                                Toast.makeText(SettingActivity.this, "MD5校验失败", Toast.LENGTH_SHORT).show();
                                appUpdateDialog.dismiss();
                                //file.delete();
                            }
                        }
                    }

                    @Override
                    public void onError(Response<File> response) {
                        Toast.makeText(SettingActivity.this, "安装包下载失败", Toast.LENGTH_SHORT).show();
                        appUpdateDialog.dismiss();
                        File mFile = new File(mSavePath + apk_name);
                        // 判断文件目录是否存在
                        if (mFile.exists()) {
                            mFile.delete();
                        }
                    }

                    @Override
                    public void downloadProgress(Progress progress) {

                        appUpdateDialog.setProgress((int) (progress.fraction * 100));

                    }
                });


    }
    //从一个url中获取文件的名称
    protected String getFileName(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBusUtils.unregister(this);
    }
}
